from django.shortcuts import render
from django.views import View
from areas.models import Area
from django import http

# 1,获取省市区
class AreaView(View):
    def get(self,request):

        # 获取参数
        area_id =  request.GET.get("area_id")

        # 查询省份数据
        if not area_id:
            provinces = Area.objects.filter(parent_id=None).all()
            # 遍历省份对象列表，拼接成字典列表
            provinces_list = []
            for province in provinces:
                provinces_list.append({
                    'id': province.id,
                    'name': province.name
                })
            context = {
                "province_list":provinces_list,
                'code':0
            }
        else:
            # 查询市或者区的数据
            subs = Area.objects.filter(parent_id=area_id)

            # 将对象列表转成字典列表
            sub_data = []
            for sub in subs:
                sub_data.append({
                    'id':sub.id,
                    'name':sub.name
                })

            context = {
                'sub_data':{
                    'subs':sub_data
                },
                'code':0
            }

        # 返回响应
        return http.JsonResponse(context)
